package com.nulldev.util.security.encryptAPI.impls.aes128_counter;

import com.nulldev.util.data.Variables;
import com.nulldev.util.data.Base64.Base64;
import com.nulldev.util.security.encryptAPI.Encryptor;

public class AES128Counter extends Encryptor {

	private final AESCipherCounter aes;

	public AES128Counter(final String key) {
		this(key.getBytes());
	}

	public AES128Counter(final byte[] key) {
		super("encryptapi.legacy.aes128_counter", new String[]
			{ "AES-Counter", "AES-128-Counter" }, key);
		this.aes = new AESCipherCounter(key);
	}

	@Override
	public byte[] encryptToBytes(Object o) {
		Variables.notNullE(o);
		if (o instanceof byte[]) {
			return aes.getEncryptedMessage((byte[]) o);
		} else if (o instanceof String) {
			return aes.getEncryptedMessage(((String) o).getBytes());
		} else {
			throw new UnsupportedOperationException("encryptToBytes() -> Unsupported operation on: " + o);
		}
	}

	@Override
	public String encrypt(Object o) {
		Variables.notNullE(o);
		if (o instanceof byte[]) {
			return Base64.encodeBase64String(aes.getEncryptedMessage((byte[]) o));
		} else if (o instanceof String) {
			return aes.getEncryptedMessage((String) o);
		} else {
			throw new UnsupportedOperationException("encrypt() -> Unsupported operation on: " + o);
		}
	}

	@Override
	public String decrypt(String o) {
		Variables.notNullE(o);
		if (o.isEmpty())
			throw new IllegalArgumentException("o is empty!");
		return aes.getDecryptedMessage((String) o);
	}

	@Override
	public byte[] decryptToBytes(byte[] o) {
		Variables.notNullE(o);
		if (o instanceof byte[]) {
			return aes.getDecryptedMessage(o);
		} else {
			throw new UnsupportedOperationException("encryptToBytes() -> Unsupported operation on: " + o);
		}
	}

	@Override
	public byte[] getKey() {
		return this.key;
	}

	@Override
	public String getKeyAsString() {
		return Base64.encodeBase64String(this.key);
	}

}
